import initDefaultData, { transformData } from '@/constants/initDefaultData.js'
import defaultConfig from '@/constants/defaultChartConf.js'
import $ from 'jquery'
import io from '@/utils/http/index.js';

export default {
  props: {
    id: {
      type: [String, Number],
      default: 'chartModule'
    },

    // 使用场所
    place: {
      type: String
    },

    type: {
      type: String
    },

    title: {
      type: String
    },

    subtitle: {
      type: String
    },

    describe: {
      type: String
    },

    // 图表显示数据
    data: {
      type: Object,
      default: null
    },

    // 数据源配置
    apiConfig: {
      type: Object
    },

    // 图表配置
    config: {
      type: Object
    },

    // 数据类型 0:静态 1:api
    dataType: {
      type: Number,
      default: 0
    }
  },

  data () {
    return {
      loading: false,

      // 图表相关配置
      chart: {
        config: {},
        apiConfig: null
      },
      
      // 组件显示数据
      showData: {
        title: '',
        describe: ''
      },

      // 图表对象
      chartObj: null,

      spinning: false
    }
  },

  created () {
    this.init()
  },

  mounted () {
    if (this.dataType === 0) {
      setTimeout(()=> {
        this.$render()
      }, 10)
    }
  },

  methods: {

    init () {
      this.chart.config =  Object.assign({}, this.config)
      this.showData = this.data || initDefaultData(this.type)
      this.requestApi()
    },
    
    // 获取api数据
    requestApi () {
      if (this.dataType === 1 && this.apiConfig) {
        this.spinning = true
        io({
          url: '/show/api/request',
          method: 'post',
          data: this.apiConfig
        }).then(res => {
          this.spinning = false
        }).catch(e => {
          this.spinning = false
        })
      }
    },

    /**
     * 数据更新，渲染图表
     */

    $changeData (showData) {
      if (showData) this.showData = showData
      const value = this.showData.value
      value !== undefined ? this.chartObj.changeData(value) : this.chartObj.changeData(transformData(this.showData))
    },

    /**
     * 更新图表配置
     */
    $updateConfig (config) {
      if (config) this.chart.config = config
      this.chartObj.update(this.chart.config)
    },

    /**
     * 容器改变大小
     */
    $changeSize (w, h) {
      const $centent = $('#' + this.id)
      this.chartObj && this.chartObj.changeSize($centent.width(), $centent.height())
    },

    /**
     * 销毁图表
     */
    $destroy () {
      this.chartObj && this.chartObj.destroy()
    }
  },

  beforeUnmount() {
    this.$destroy()
  }
}